from .models import *
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers

class CommentSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    class Meta:
        model = Comment
        fields = ('id', 'content', 'comment_time', 'student_id')

class SubjectSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    comment = serializers.SerializerMethodField(allow_null=True)

    class Meta:
        model = Subject
        fields = ('id', 'title', 'answer', 'company', 'address', 'student_id', 'student_name', 'subject', 'classroom', 'collection_num', 'click_num', 'add_time', 'teacher_id', 'state', 'comment')

    def get_comment(self, obj):
        comments = obj.comment.all()
        ser = CommentSerializer(comments, many=True)
        return ser.data

class CollectionSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    subject_id = serializers.SerializerMethodField(allow_null=True)
    class Meta:
        model = Collection
        fields = ('id', 'subject_id', 'collection_time', 'student_id')


class UserSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    roles = serializers.SerializerMethodField(allow_null=True)
    class Meta:
        model = User
        fields = ('id', 'account', 'pwd', 'name', 'type', 'photo', 'roles')

class SubjectRoleSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    class Meta:
        model = SubjectRole
        fields = ('id', 'role')
